/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: Dec 31, 2009
 * Time: 11:03:36 AM
 * To change this template use File | Settings | File Templates.
 */
import org.jdom.Element;

// Referenced classes of package dk.brics.dsd:
//            Field, Context, FieldEvaluationException, Boolexp,
//            Validator, Schema

class ChardataField extends Field
{

    ChardataField(Element element, Schema schema)
    {
        exp = Boolexp.parseOneOptional(element, schema);
        String s = element.getAttributeValue("type");
        qname = s != null && s.equals("qname");
        qaname = s != null && s.equals("qaname");
    }

    public String evaluate(Context context, Element element)
        throws FieldEvaluationException
    {
        error = false;
        Element element1 = findSelected(new Context(element, context.e, context.v), exp);
        if(element1 == null)
            throw new FieldEvaluationException("not exactly one element selected at chardata field");
        String s = Validator.whitespaceString(true, element1.getText());
        if(qname || qaname)
        {
            s = fixQname(s, element1, qaname);
            if(s == null)
                throw new FieldEvaluationException(qname ? "invalid qname" : "invalid qaname");
        }
        return s;
    }

    public Element toXML(Context context)
    {
        Element element = new Element("chardatafield", "http://www.brics.dk/DSD/2.0");
        if(exp != null)
            element.addContent(exp.toXML(context));
        if(qname)
            element.setAttribute("type", "qname");
        else
        if(qaname)
            element.setAttribute("type", "qaname");
        return element;
    }

    Boolexp exp;
    boolean qname;
    boolean qaname;
}
